using Eno.Application.Services;
using Eno.Infrastructure.Tools;
using Microsoft.AspNetCore.Mvc;
using Eno.Domain.Entity.App;

namespace Eno.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class DashboardController : ControllerBase
{
    private readonly UserService _userService;
    private readonly RoleService _roleService;
    private readonly PermissionService _permissionService;
    private readonly DepartmentService _departmentService;

    public DashboardController(
        UserService userService,
        RoleService roleService,
        PermissionService permissionService,
        DepartmentService departmentService)
    {
        _userService = userService;
        _roleService = roleService;
        _permissionService = permissionService;
        _departmentService = departmentService;
    }

    [HttpGet("statistics")]
    public async Task<IActionResult> GetStatistics()
    {
        try
        {
            var users = await _userService.SelectUser();
            var roles = await _roleService.GetAllRolesAsync();
            var permissions = await _permissionService.GetAppPermissionsAsync();
            var departmentsResult = await _departmentService.GetDepartmentAsync();
 
            System.Console.WriteLine(users);
            // 处理部门数据的返回类型
            int departmentsCount = 0;
            if (departmentsResult is Tips<IEnumerable<AppDepartment>> tips && tips.Value != null)
            {
                departmentsCount = tips.Value.Count();
            }

            var statistics = new
            {
                users = users?.Count() ?? 0,
                roles = roles?.Count() ?? 0,
                permissions = permissions?.Count() ?? 0,
                departments = departmentsCount
            };

            return Ok(Tips<object>.Success(statistics, "获取统计数据成功"));
        }
        catch (Exception ex)
        {
            return Ok(Tips<string>.Fail($"获取统计数据失败: {ex.Message}"));
        }
    }

    [HttpGet("chart-data")]
    public async Task<IActionResult> GetChartData()
    {
        try
        {
            // 1. 部门用户分布数据
            var users = await _userService.SelectUser() ?? Enumerable.Empty<AppUser>();
            var departments = await _departmentService.GetDepartmentAsync();
            
            var departmentUserCount = new Dictionary<string, int>();
            if (departments is Tips<IEnumerable<AppDepartment>> deptTips && deptTips.Value != null)
            {
                foreach (var dept in deptTips.Value)
                {
                    var userCount = users.Count(u => u.DepartmentID == dept.ID);
                    departmentUserCount[dept.DepartName] = userCount;
                }
            }

            // 2. 权限分布数据
            var permissions = await _permissionService.GetAppPermissionsAsync() ?? Enumerable.Empty<AppPermission>();
            
            // 调试：打印权限名称
            System.Console.WriteLine("权限列表:");
            foreach (var perm in permissions)
            {
                System.Console.WriteLine($"权限名称: {perm.PermissionName}");
            }
            
            var permissionTypes = permissions.GroupBy(p => 
            {
                var name = p.PermissionName?.ToLower() ?? "";
                
                // 读权限 - 查询、查看、读取相关
                if (name.Contains("read") || name.Contains("查询") || name.Contains("查看") || name.Contains("get") || 
                    name.Contains("select") || name.Contains("list") || name.Contains("find") || name.Contains("search") ||
                    name.Contains("query")) 
                    return "读权限";
                
                // 写权限 - 创建、更新、删除、编辑、审批相关
                if (name.Contains("write") || name.Contains("创建") || name.Contains("更新") || name.Contains("删除") || 
                    name.Contains("post") || name.Contains("put") || name.Contains("delete") || name.Contains("create") || 
                    name.Contains("update") || name.Contains("edit") || name.Contains("add") || name.Contains("remove") ||
                    name.Contains("approve") || name.Contains("reject")) 
                    return "写权限";
                
                // 管理权限 - 管理、配置、设置相关
                if (name.Contains("admin") || name.Contains("管理") || name.Contains("配置") || name.Contains("设置") || 
                    name.Contains("manage") || name.Contains("config") || name.Contains("assign") || name.Contains("分配") ||
                    name.Contains("role") || name.Contains("permission") || name.Contains("user")) 
                    return "管理权限";
                
                // 如果权限名称很短或无法分类，根据权限数量智能分配
                if (name.Length <= 3) return "读权限"; // 短名称通常是基础权限
                if (name.Contains("system") || name.Contains("log") || name.Contains("backup")) return "管理权限";
                
                return "写权限"; // 默认归类为写权限
            })
            .Select(g => new { name = g.Key, value = g.Count() })
            .ToList();
            
            // 确保至少有三个类别，如果某个类别为空，添加默认值
            var categoryNames = new[] { "读权限", "写权限", "管理权限" };
            var existingCategories = permissionTypes.Select(p => p.name).ToHashSet();
            
            foreach (var category in categoryNames)
            {
                if (!existingCategories.Contains(category))
                {
                    permissionTypes.Add(new { name = category, value = 0 });
                }
            }
            
            // 按类别名称排序，确保显示顺序一致
            permissionTypes = permissionTypes.OrderBy(p => p.name).ToList();
            
            // 调试：打印分类结果
            System.Console.WriteLine("权限分类结果:");
            foreach (var type in permissionTypes)
            {
                System.Console.WriteLine($"{type.name}: {type.value}");
            }

            // 3. 模拟活动趋势数据（7天）
            var activityTrend = new List<object>();
            var random = new Random();
            for (int i = 6; i >= 0; i--)
            {
                var date = DateTime.UtcNow.AddDays(-i).Date;
                var dayLogs = random.Next(5, 25); // 模拟数据
                activityTrend.Add(new { date = date.ToString("MM-dd"), count = dayLogs });
            }

            // 4. 模拟最近活动
            var recentActivities = new List<object>
            {
                new { user = "admin", action = "登录了系统", time = "刚刚", avatar = "" },
                new { user = "张三", action = "创建了新用户", time = "2分钟前", avatar = "" },
                new { user = "李四", action = "更新了角色权限", time = "5分钟前", avatar = "" },
                new { user = "王五", action = "导出了用户数据", time = "10分钟前", avatar = "" }
            };

            // 5. 系统状态（模拟数据）
            var systemStatus = new
            {
                cpu = new Random().Next(30, 80),
                memory = new Random().Next(40, 90),
                disk = new Random().Next(50, 95)
            };

            var chartData = new
            {
                departmentUserCount,
                activityTrend,
                permissionTypes,
                recentActivities,
                systemStatus
            };

            return Ok(Tips<object>.Success(chartData, "获取图表数据成功"));
        }
        catch (Exception ex)
        {
            return Ok(Tips<string>.Fail($"获取图表数据失败: {ex.Message}"));
        }
    }

    [HttpGet("recent-logins")]
    public IActionResult GetRecentLogins()
    {
        try
        {
            // 模拟最近登录数据
            var loginLogs = new List<object>
            {
                new { id = 1, username = "admin", time = "刚刚", avatar = "" },
                new { id = 2, username = "zhangsan", time = "2分钟前", avatar = "" },
                new { id = 3, username = "lisi", time = "5分钟前", avatar = "" },
                new { id = 4, username = "wangwu", time = "10分钟前", avatar = "" }
            };

            return Ok(Tips<object>.Success(loginLogs, "获取最近登录成功"));
        }
        catch (Exception ex)
        {
            return Ok(Tips<string>.Fail($"获取最近登录失败: {ex.Message}"));
        }
    }



    private string GetPermissionCategory(string permissionName)
    {
        var name = permissionName?.ToLower() ?? "";
        
        // 读权限 - 查询、查看、读取相关
        if (name.Contains("read") || name.Contains("查询") || name.Contains("查看") || name.Contains("get") || 
            name.Contains("select") || name.Contains("list") || name.Contains("find") || name.Contains("search") ||
            name.Contains("query")) 
            return "读权限";
        
        // 写权限 - 创建、更新、删除、编辑、审批相关
        if (name.Contains("write") || name.Contains("创建") || name.Contains("更新") || name.Contains("删除") || 
            name.Contains("post") || name.Contains("put") || name.Contains("delete") || name.Contains("create") || 
            name.Contains("update") || name.Contains("edit") || name.Contains("add") || name.Contains("remove") ||
            name.Contains("approve") || name.Contains("reject")) 
            return "写权限";
        
        // 管理权限 - 管理、配置、设置相关
        if (name.Contains("admin") || name.Contains("管理") || name.Contains("配置") || name.Contains("设置") || 
            name.Contains("manage") || name.Contains("config") || name.Contains("assign") || name.Contains("分配") ||
            name.Contains("role") || name.Contains("permission") || name.Contains("user")) 
            return "管理权限";
        
        // 如果权限名称很短或无法分类，根据权限数量智能分配
        if (name.Length <= 3) return "读权限"; // 短名称通常是基础权限
        if (name.Contains("system") || name.Contains("log") || name.Contains("backup")) return "管理权限";
        
        return "写权限"; // 默认归类为写权限
    }
}